package com.glacier.demo.contoller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * date 2024-01-29 19:55
 *
 * @author glacier
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/degrade")
public class DegradeController {

    @PostConstruct
    public void initRule() {
        List<FlowRule> rules = new ArrayList<>();

        FlowRule rule = new FlowRule();
        rule.setResource("flow1");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(2);
        rules.add(rule);

        FlowRule rule1 = new FlowRule();
        rule1.setResource("flow2");
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule1.setCount(2);
        rules.add(rule1);

        FlowRuleManager.loadRules(rules);
    }

    @RequestMapping("/test1")
    public String test1() {
        try (Entry entry = SphU.entry("flow1")) {
            return "正常访问";
        } catch (BlockException e) {
            log.error("流控了", e);
            return "流控了!";
        }
    }

    @RequestMapping("/test2")
    @SentinelResource(value = "flow2", blockHandler = "flowHandleException")
    public String test2() {
        return "正常访问";
    }

    public String flowHandleException(BlockException ex) {
        log.error("流控了", ex);
        return "流控了";
    }
}
